﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using server.Communication;
using server.Communication.Messages;
using server.DataBase;

namespace server
{
    class Server
    {
        private string ip;
        private int port = 8000;
        private Protocol protocol;
        private Data mainPage;
        private ServerMessageHandler msgHandler;
        private bool isRunning;


        public Server(string ipAdrr, int port, Data data)
        {
            this.ip = ipAdrr;
            this.port = port;
            this.protocol = new Protocol();
            this.mainPage = data;
            this.msgHandler = null;
            this.isRunning = false;
        }

        public void initServer()
        {
            try
            {
                ArrayList cls = new ArrayList();
                ArrayList clients = ArrayList.Synchronized(cls);

                this.isRunning = true;
                IPAddress ipAdrr = IPAddress.Parse(this.ip);
                TcpListener server = new TcpListener(ipAdrr, 8000);
                server.Start();

                while (isRunning)
                {
                    try
                    {
                        TcpClient client_socket = server.AcceptTcpClient();
                        ClientHandler client = new ClientHandler();
                        clients.Add(client);

                        client.startClient(client_socket, mainPage);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                        this.isRunning = false;
                        server.Stop();
                    }
                }
                Console.ReadLine();

                //strm.Close();
                //client.Close();
                server.Stop();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

    }
}
